// request.ts
import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'
import storage from './storage'
export interface IResponse<T> {
  code: number
  result: T
  message: string
}
interface IOpts {
  url: string
  method: string
  headers?: object
  params?: object | string
  data?: object | string
}

export class Request {
  private request<T>(opts: IOpts) {
    const instance: AxiosInstance = axios.create({
      baseURL: '',
      timeout: 6000
    })
    this.setInterceptors(instance)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return instance<any, IResponse<T>>(opts)
  }

  private setInterceptors(ins: AxiosInstance) {
    ins.interceptors.request.use((config) => {
      return config
    })

    ins.interceptors.response.use((res: AxiosResponse) => {
      if (res.status === 200) {
        return res.data
      } else {
        console.log('接口错误')
      }
    })
  }
  private headers: Object
  constructor() {
    this.headers = {
      token: storage.get('token')
    }
  }
  get<T>(url: string, options?: object | string) {
    return this.request<T>({
      url,
      method: 'get',
      headers: this.headers,
      params: options
    })
  }

  post<T>(url: string, options?: object | string) {
    return this.request<T>({
      url,
      method: 'post',
      // headers: {
      //   'Content-Type':'application/x-www-form-urlencoded'
      // },
      headers: this.headers,
      data: options
    })
  }
}

const request = new Request()

export default request
